<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>产品管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-row>
      <el-col :span="24">
        <el-button
          type="primary"
          icon="el-icon-edit"
          @click="dialogFormVisible = true"
          >新增</el-button
        >
        <el-button type="danger" icon="el-icon-delete">批量删除</el-button>

        <!-- 新增按钮弹出框 -->
        <el-dialog title="产品信息" :visible.sync="dialogFormVisible">
          <el-form :model="form">
            <el-form-item label="产品名称" label-width="120px">
              <el-input v-model="form.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="产品价格" label-width="120px">
              <el-input v-model="form.pname" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="产品图片" label-width="120px">
              <el-upload
                class="upload-demo"
                action="https://jsonplaceholder.typicode.com/posts/"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :file-list="fileList"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-form-item>
            <el-form-item label="产品库存" label-width="120px">
              <el-input v-model="form.price" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="产品描述" label-width="120px">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
                v-model="form.remark"
              ></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="addAddress">确 定</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>

    <!-- 表格区域 -->
    <el-table
      :data="ProductData"
      height="400"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      :row-class-name="tableRowClassName"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="id" label="编号" width="50"></el-table-column>
      <el-table-column prop="img" label="图片"></el-table-column>
      <el-table-column prop="name" label="产品名称"></el-table-column>
      <el-table-column prop="level1" label="分类1"></el-table-column>
      <el-table-column prop="level2" label="分类2"></el-table-column>
      <el-table-column prop="level3" label="分类3"></el-table-column>
      <el-table-column prop="price" label="价格"></el-table-column>
      <el-table-column prop="stock" label="库存"></el-table-column>      
      <el-table-column prop="desc" label="描述"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)"
            v-on:click="dialog = true"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row.id)"
            >删除</el-button
          >

          <!-- 编辑按钮弹出框 -->
          <el-drawer
            title="编辑收货地址"
            :before-close="handleClose"
            :visible.sync="dialog"
            direction="ltr"
            custom-class="demo-drawer"
            ref="drawer"
          >
            <div class="demo-drawer__content">
              <el-form :model="form">
                <el-form-item label="收货人姓名" label-width="80px">
                  <el-input v-model="form.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="详细地址" label-width="80px">
                  <el-input
                    v-model="form.address"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
                <el-form-item label="收货日期" label-width="80px">
                  <el-date-picker
                    v-model="form.date"
                    align="right"
                    type="date"
                    placeholder="选择日期"
                    :picker-options="pickerOptions"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item label="是否默认" label-width="80px">
                  <template>
                    <!-- Switch 开关组件 -->
                    <!-- v-model="scope.row.isDefault" 数据根据当前域每一行的isDefault更改 -->
                    <el-switch
                      v-model="form.isDefault"
                      active-color="#13ce66"
                      inactive-color="#ff4949"
                      :active-value="1"
                      :inactive-value="0"
                    ></el-switch>
                  </template>
                </el-form-item>
                <el-form-item label="备注" label-width="80px">
                  <el-input
                    type="textarea"
                    :rows="2"
                    placeholder="请输入内容"
                    v-model="form.remark"
                  ></el-input>
                </el-form-item>
              </el-form>
              <div class="demo-drawer__footer">
                <el-button @click="cancelForm">取 消</el-button>
                <el-button
                  type="primary"
                  @click="editAddress"
                  :loading="loading"
                  >{{ loading ? "提交中 ..." : "确 定" }}</el-button
                >
              </div>
            </div>
          </el-drawer>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageParam.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="22"
      >
      </el-pagination>
    </div>
  </div>
</template>

// js样式
<script>
export default {
  data() {
    return {
        //图片上传的数据
      fileList: [{name: '', url: ''}],
      table: false,
      dialog: false,
      loading: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      tableData: [],
      ProductData: [],
      multipleSelection: [],
      dialogFormVisible: false,
      form: {
        id: 0,
        name: "",
        price: "",
        stock: "",
        desc: "",
        level1:"",
        level2: "",
        level3: "",
        img: "",        
      },
      pageParam: {
        pageNumber: 1,
        pageSize: 10,
      },
      formLabelWidth: "120px",
      timer: null,
    };
  },
  methods: {
      //上传图片的方法
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
    //新增产品的方法
    addAddress() {
      console.log(this.form);
      //提交数据
      if (this.form.uname.length > 0 && this.form.pname.length > 0) {
        this.$axios.post("/product", this.form).then((res) => {
          console.log(res);
          //重新加载页面
          if (res.status == 201) {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.loadData();
          } else {
            this.$message.error("数据出错，请重新加载");
          }
        });
      }
      this.dialogFormVisible = false;
    },
    //是否默认操作修改 默认地址开关发生改变时得到的当前数据row.id
    isDefaultMsg(row) {
      console.log(row);
      let index = this.ProductData.findIndex((isDefaultIds) => {
        return isDefaultIds.id == row.id;
      });
      console.log(index);
      //判断当前行的isDefault的值是否与后台数据相等
      if (!row.isDefault == this.ProductData[index].isDefault) {
        this.ProductData[index].isDefault = row.isDefault;
      }
      console.log(this.ProductData[index].isDefault);
      console.log(this.ProductData[index].id);
      this.$axios
        .put(
          "/product" + this.ProductData[index].id,
          this.ProductData[index]
        )
        .then((res) => {
          console.log(res);
          //判断是否成功修改
          if (res.status == 200) {
            this.$message({
              showClose: true,
              message: "用户信息修改成功",
              type: "success",
            });
          }

          this.loadData(); //重新渲染数据
        });
    },
    //页面加载数据
    loadData: function () {
      this.$axios
        .get(
          "http://localhost:3000/product?_page=" +
            this.pageParam.pageNumber +
            "&_limit=" +
            this.pageParam.pageSize
        )
        .then((res) => {
          console.log(res);
          this.ProductData = res.data;
        });
    },
    //默认选项的开关事件
    tableRowClassName({ row, rowIndex }) {
      if (row.isDefault == "1") {
        return "warning-row";
      } else if (row.isDefault == "0") {
        return "Default-row";
      }
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    handleClose(done) {
      if (this.loading) {
        return;
      }
      this.$confirm("确定要提交表单吗？")
        .then((_) => {
          this.loading = true;
          this.timer = setTimeout(() => {
            done();
            // 动画关闭需要一定的时间
            setTimeout(() => {
              this.loading = false;
            }, 400);
          }, 2000);
        })
        .catch((_) => {});
    },
    //关闭弹出框
    cancelForm() {
      this.loading = false;
      this.dialog = false;
      clearTimeout(this.timer);
    },
    //编辑按钮方法
    handleEdit(index, row) {
      console.log(index, row);
      this.form.id = row.id;
      this.form.name = row.name;
      this.form.address = row.address;
      this.form.date = row.date;
      this.form.isDefault = row.isDefault;
      this.form.remark = row.remark;
    },
    //编辑后提交新数据
    editAddress() {
      this.$axios
        .put("/product/" + this.form.id, this.form)
        .then((res) => {
          if (res.status == 200) {
            this.$message({
              type: "success",
              message: "修改成功!",
            });
            this.dialog = false;
            this.loadData();
          }
        });
    },
    //删除按钮方法
    handleDelete(id) {
      console.log(id);
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios.delete("/product/" + id).then((res) => {
            if (res.status == 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            }
            this.loadData();
          });
        })
        .catch(() => {});
    },
    //分页方法
    //每页数据量发生变化时触发的事件
    handleSizeChange(pageSize) {
      this.pageParam.pageSize = pageSize;
      this.loadData();
    },
    //当前数据分页组件页码发生变化时触发的事件
    handleCurrentChange(val) {
      this.pageParam.pageNumber = val;
      this.loadData();
    },
  },
  mounted: function () {
    this.loadData();
  },
};
</script>

// CSS样式
  <style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
.el-row {
  margin-top: 20px;
  margin-bottom: 20px;
}

.el-col {
  border-radius: 4px;
}
</style>